import axios from 'axios'
import { Message } from 'element-ui'
import pickBy from 'lodash/pickBy'
import store from '@/store'
import Vue from 'vue'
// import { getToken } from '@/utils/auth'

const codeMessage = {
  200: '服务器成功返回请求的数据。',
  201: '新建或修改数据成功。',
  202: '一个请求已经进入后台排队（异步任务）。',
  204: '删除数据成功。',
  400: '发出的请求有错误，服务器没有进行新建或修改数据的操作。',
  401: '用户没有权限（令牌、用户名、密码错误）。',
  403: '用户得到授权，但是访问是被禁止的。',
  404: '发出的请求针对的是不存在的记录，服务器没有进行操作。',
  406: '请求的格式不可得。',
  410: '请求的资源被永久删除，且不会再得到的。',
  422: '当创建一个对象时，发生一个验证错误。',
  500: '服务器发生错误，请检查服务器。',
  502: '网关错误。',
  503: '服务不可用，服务器暂时过载或维护。',
  504: '网关超时。'
}

/**
 * 异常处理程序
 */
const errorHandler = (error) => {
  const response = error.response || {}
  const errortext = codeMessage[response.status] || response.statusText
  const { status } = response
  if (status === 401) {
    Message({
      message: '未登录或登录已过期，请重新登录。',
      type: 'error'
    })
    store.dispatch('user/resetToken').then(() => {
      location.reload()
    })
    return
  }

  Message.error({
    message: errortext || 'Error',
    type: 'error'
  })
  return Promise.reject(error)
}

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// 去空
function emptyFlag (value) {
  return value != null
}
// request interceptor
service.interceptors.request.use(
  (config) => {
    // do something before request is sent

    // 去除空对象
    if (config.params) {
      config.params = pickBy(config.params, (value) => {
        return emptyFlag(value)
      })
    }
    if (
      config.data &&
      Object.prototype.toString.call(config.data) !== '[object FormData]'
    ) {
      config.data = pickBy(config.data, (value) => {
        return emptyFlag(value)
      })
    }

    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers.ticket = store.getters.token
    }
    config.headers.platformId = process.env.VUE_APP_PLATFORMID
    return config
  },
  (error) => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  (response) => {
    const res = response.data
    // if the custom code is not 20000, it is judged as an error.
    if (res.code === Vue.prototype.$successCode) {
      return res.data
    } else if (
      res.type ===
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    ) {
      return res
    } else {
      Message({
        message: res.msg || 'Error',
        type: 'error',
        duration: 5 * 1000
      })
      if (res.code === '910000' || res.code === '000001') {
        store.dispatch('user/logout').then(() => {
          location.reload()
        })
      }
      // store.dispatch('user/resetToken').then(() => {
      //   location.reload()
      // })
      return Promise.reject(new Error(res.message || 'Error'))
    }
  },
  errorHandler
)

export default service
